import core from '@/core/'
import handleFail from "./handleFail"
import handleUserInfo from "./handleUserInfo"
/**
 * 成功的统一处理
 */
module.exports = (res, config, resolve, reject, again, callback) => {	
	const {src, loading, name, showConsole, userKeys, reuserinfo, loadingText, mask, complete} = config
	if (res) {
		const TypeIsObject = Object.prototype.toString.call(res) === '[object Object]'
		var {error, errCode, errMsg, data, message, toast, modal, current, timeCost, requestId, inserted, deleted, updated, pagination, status} = TypeIsObject ? res : {}
		if (current) { // 记录服务器的时间
			core.store.current = current
		}
		if (res['Ca-Token']) { // 记录用户Token
			core.request.token = res['Ca-Token']
		}
		if (showConsole) {
			console.log(`${name} - 结束请求${timeCost ? ` - 响应时间：${timeCost}毫秒 - ` : '：'}${current ? (core.time.getString(current) + ' - ') : ''}${requestId || '没有请求id'}`)
			if (status === 200 || !TypeIsObject) {
				console.log(`${name} - 请求成功：${(message ? message : toast) || ''}`)
				if (modal) {
					uni.showModal({
						title: '请求结果',
						content: modal,
						showCancel: false,
						confirmText: '我知道了'
					})
				} else if (toast) {
					core.showToast(toast)
				}
				if (data) {
					console.log(data)
				} else {
					console.log(res)
				}
			} else {
				console.error(`${name} - 请求失败：`)
				if (message) {
					console.error(message)
				} else if (error) {
					console.error(error)
				}
				console.log(res)
			}
		}
		if (!error && (errCode || errMsg)) {
			error = {errCode, errMsg}
		}
		if (error) {
			handleFail(error, config, reject, again)
			callback && callback(res)
		} else {
			handleUserInfo(res.data, config).then(data => {
				res.data = data
				resolve(res)
				callback && callback(res)
			}).catch(err => {
				console.warn('用户信息处理失败')
				resolve(res)
				callback && callback(res)
			})
		}
	} else {
		console.log('没有任何数据返回')
		reject('没有任何数据返回')
		callback && callback(res)
	}
}